package com.example.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;

/**
 * 全局异常处理器
 * 
 * @author Means
 * @since 2025-10-27
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    
    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiResponse<?> handleBusinessException(BusinessException e, HttpServletRequest request) {
        logger.warn("业务异常: {}, 路径: {}", e.getMessage(), request.getRequestURI());
        return ApiResponse.error(e.getErrorCode(), e.getErrorMessage())
                .withPath(request.getRequestURI());
    }
    
    /**
     * 处理资源未找到异常
     */
    @ExceptionHandler(ResourceNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ApiResponse<?> handleResourceNotFoundException(ResourceNotFoundException e, HttpServletRequest request) {
        logger.warn("资源未找到: {}, 路径: {}", e.getMessage(), request.getRequestURI());
        return ApiResponse.error(e.getErrorCode(), e.getErrorMessage())
                .withPath(request.getRequestURI());
    }
    
    /**
     * 处理参数校验异常 (@Valid)
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiResponse<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
        String errorMessage = e.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining("; "));
        
        logger.warn("参数校验失败: {}, 路径: {}", errorMessage, request.getRequestURI());
        return ApiResponse.error(ErrorCode.PARAMETER_ERROR, errorMessage)
                .withPath(request.getRequestURI());
    }
    
    /**
     * 处理参数绑定异常
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiResponse<?> handleBindException(BindException e, HttpServletRequest request) {
        String errorMessage = e.getBindingResult().getFieldErrors().stream()
                .map(error -> error.getField() + ": " + error.getDefaultMessage())
                .collect(Collectors.joining("; "));
        
        logger.warn("参数绑定失败: {}, 路径: {}", errorMessage, request.getRequestURI());
        return ApiResponse.error(ErrorCode.PARAMETER_ERROR, errorMessage)
                .withPath(request.getRequestURI());
    }
    
    /**
     * 处理参数约束违反异常
     */
    @ExceptionHandler(ConstraintViolationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiResponse<?> handleConstraintViolationException(ConstraintViolationException e, HttpServletRequest request) {
        String errorMessage = e.getConstraintViolations().stream()
                .map(ConstraintViolation::getMessage)
                .collect(Collectors.joining("; "));
        
        logger.warn("参数约束违反: {}, 路径: {}", errorMessage, request.getRequestURI());
        return ApiResponse.error(ErrorCode.PARAMETER_ERROR, errorMessage)
                .withPath(request.getRequestURI());
    }
    
    /**
     * 处理非法参数异常
     */
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ApiResponse<?> handleIllegalArgumentException(IllegalArgumentException e, HttpServletRequest request) {
        logger.warn("非法参数: {}, 路径: {}", e.getMessage(), request.getRequestURI());
        return ApiResponse.error(ErrorCode.PARAMETER_ERROR, e.getMessage())
                .withPath(request.getRequestURI());
    }
    
    /**
     * 处理空指针异常
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiResponse<?> handleNullPointerException(NullPointerException e, HttpServletRequest request) {
        logger.error("空指针异常, 路径: {}", request.getRequestURI(), e);
        return ApiResponse.error(ErrorCode.SYSTEM_ERROR, "系统内部错误")
                .withPath(request.getRequestURI());
    }
    
    /**
     * 处理其他未捕获异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ApiResponse<?> handleException(Exception e, HttpServletRequest request) {
        logger.error("系统异常, 路径: {}", request.getRequestURI(), e);
        return ApiResponse.error(ErrorCode.SYSTEM_ERROR, "系统错误，请稍后重试")
                .withPath(request.getRequestURI());
    }
}

